package com.quantumoctopus.magiceatball;

import java.util.StringTokenizer;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;

public class ResultActivity extends Activity {

	private TextView nameTextView;
	private TextView addressTextView;
	private TextView phoneTextView;
	private TextView urlTextView;
	private TextView priceTextView;
	private RatingBar ratingBar;
	private String name;
	private String id;
	public static final String PREFS_EATBALL = "EatBallPrefsFile";
	static SharedPreferences settings;
	SharedPreferences.Editor editor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.result_activity_layout);
		nameTextView = (TextView) findViewById(R.id.nameTextView);
		addressTextView = (TextView) findViewById(R.id.addressTextView);
		phoneTextView = (TextView) findViewById(R.id.phoneTextView);
		urlTextView = (TextView) findViewById(R.id.urlTextView);
		priceTextView = (TextView) findViewById(R.id.priceTextView);
		ratingBar = (RatingBar) findViewById(R.id.ratingBar1);

		Intent intent = getIntent();
		name = intent.getStringExtra("name");
		id = intent.getStringExtra("id");
		String[] display_addressArray = intent
				.getStringArrayExtra("display_address");
		String url = intent.getStringExtra("url");
		String phone = intent.getStringExtra("phone");
		String price = intent.getStringExtra("price");
		Float rating = intent.getFloatExtra("rating", 0);

		nameTextView.setText(name);
		urlTextView.setText(url);
		phoneTextView.setText(phone);
		priceTextView.setText(price);
		ratingBar.setRating(rating);
		

		// build address string from array
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < display_addressArray.length; i++) {
			sb.append(display_addressArray[i]);
			if (i != (display_addressArray.length - 1))
				sb.append("\n");
		}
		String display_address = sb.toString();
		display_address = display_address.replace("\"", "");
		addressTextView.setText(display_address);

		Logresult();
	}

	public void Logresult()/* Saves result to log in format of ";;Name::Id" */
	{
		settings = getSharedPreferences(PREFS_EATBALL, 0);
		editor = settings.edit();
		String log = settings.getString("savedlogslist", "");
		if (!log.contains(id)) {
			StringBuilder sb1 = new StringBuilder();
			sb1.append(log);
			if (!log.isEmpty()) {
				sb1.append(";;");
			}
			sb1.append(name);
			sb1.append("::");
			sb1.append(id);
			String logstr = sb1.toString();
			editor.putString("savedlogslist", logstr);
			editor.commit();
		}
	}
}
